#define OS_PORT_VERSION 100					//Version number of the qOS LINUX port

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>

#include "os_cpu.h"
#include "os_cfg.h"
#include "qos.h"

sigset_t block_mask;


// debug manager------------------------
void qos_verify_process( const char * const exp, const char * const file_name, int line ){
    printf("verify FAIL:%s file:%s @%d\n", exp, file_name, line);
    exit(0);
}




void ctrl_break_handler(int ctrl){
    if (ctrl==SIGTSTP){					//Handler if CTRL-D is pressed
        printf("---Exiting -------------\n");	
                                        //---Display current task priority
    } 
    else if (ctrl==SIGINT){			    //Handler if CTRL-C is pressed
        printf("---Exiting -------------\n");	
                                        //---Display current task priority and exit
 	    exit(0);
    }
    else{
        // unexpected signal
        qos_verify( false );
    }

    return;
}



static void os_time_tick_callback(int ctrl){
    qos_verify( SIGALRM == ctrl );
    //printf("---time tick -----\n");
    qos_time_tick_isr();
}




void qqos_enable_timer_signal(void){
    if( sigprocmask( SIG_UNBLOCK, &block_mask, NULL ) < 0 ){
        qos_verify( false );
    }
}




void qqos_disable_timer_signal(void){
    if( sigprocmask( SIG_BLOCK, &block_mask, NULL ) < 0 ){
        qos_verify( false );
    }
}




bool qos_time_tick_init(void){
    struct itimerval timer_val;
    int rc=0;

    sigemptyset( &block_mask );
    sigaddset( &block_mask, SIGALRM );

    if( ( SIG_ERR == signal( SIGINT,  ctrl_break_handler ) )
        || ( SIG_ERR == signal( SIGTSTP, ctrl_break_handler ) )
        || ( SIG_ERR == signal( SIGALRM, os_time_tick_callback ) ) ){
        qos_verify( false );
    	exit(-1);
        return false;
     }

    timer_val.it_interval.tv_sec = ((int)(1000000/ OS_TICKS_PER_SEC)) / 1000000;
    timer_val.it_interval.tv_usec = ((int)(1000000/ OS_TICKS_PER_SEC)) % 1000000;
    timer_val.it_value = timer_val.it_interval;
    if (rc = setitimer(ITIMER_REAL, &timer_val, NULL)){	
        printf("ERROR: Timer could not be installed, return: %d\n", rc);
        qos_verify( false );
    	exit(-1);
        return false;
    }
    
    return true;
}



// no more
